//
// Created by root on 24-7-12.
//
typedef struct gate_desc{
    unsigned short offset_low_world;
    unsigned short segement_selctor;
    unsigned char dword;
    unsigned char attr;
    unsigned short offset_up_world;
}gate_desc;

gate_desc idt[0x22];

typedef void * inthandler;

extern inthandler int_entry_table[0x22] ;


void make_idt_describer(gate_desc * gate,inthandler function,unsigned char attr) {
    gate->offset_low_world = (unsigned short)((unsigned int)function & 0x0000ffff);
    gate->offset_up_world = (unsigned short)(((unsigned int)function & 0xffff0000)>>16);
    gate->dword = 0x0;
    gate->attr= attr;
    gate->segement_selctor = (unsigned short)0x8;
}
void rollup();
void printk(char *prompt, ...);
void current_print_position_to_nextline();
void idt_describer_init() {
    for (int i = 0;i<0x22;i++) {
        make_idt_describer(&idt[i],int_entry_table[i],0x8E);
    }
    printk("idt describer init complete");
    rollup();
}
#include "../include/io.h"
void pic_init() {
    //master ctl
    outbyte(0x20,0x11 );
    outbyte(0x21,0x20 );
    outbyte(0x21,0x04 );
    outbyte(0x21,0x03 );
    //slave ctl
    outbyte(0xa0,0x11 );
    outbyte(0xa1,0x28 );
    outbyte(0xa1,0x02 );
    outbyte(0xa1,0x03 );

    outbyte(0x21,0xFC);
    outbyte(0xa1,0xFF);



}

void idt_init() {
    idt_describer_init();
    pic_init();
    unsigned long long int idt_loader= (sizeof(idt)-1)|(((unsigned long long int)((unsigned int)idt))<<16);
    __asm__ __volatile__ ("lidt %0" : :"m"(idt_loader));
    printk("idt basaddr %d",(unsigned int)idt);
    rollup();
    printk("idt len %d",sizeof(idt));
    rollup();
    printk("load idt complete");
    rollup();

    __asm__ __volatile__ ("xchg %bx,%bx");

}